package com.intramirror.product.service.impl;

import com.intramirror.product.entity.ImPriceDiscountMapping;
import com.intramirror.product.mapper.ProductDiscountMapper;
import com.intramirror.product.service.IDiscountService;
import com.intramirror.product.service.IPriceRuleService;
import com.intramirror.product.utils.LoggerUtils;
import com.intramirror.product.vo.ProductDiscount;
import com.intramirror.utils.transform.JsonTransformUtil;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class DiscountServiceImpl implements IDiscountService {

    private static final String logger_key = "api_update_discount";

    private static final Long boutiqueType = 1L;

    private static final Long imType = 3L;

    @Autowired
    private ProductDiscountMapper productDiscountMapper;

    @Autowired
    private IPriceRuleService iPriceRuleService;

    @Override
    public void updateProductDiscountById(Long productId) {
        Map<String, Object> productMap = productDiscountMapper.getProduct(productId);
        Map<String, Object> data = this.discount(productMap);
        LoggerUtils.info(logger_key, "updateProductDiscountById,data:{},productMap:{}", JsonTransformUtil.toJson(data), JsonTransformUtil.toJson(productMap));

        int imDiscount = ((ProductDiscount) data.get("imDiscount")).getDiscount();
        int inDiscount = ((ProductDiscount) data.get("inDiscount")).getDiscount();
        productDiscountMapper.updateProductPrice(inDiscount, imDiscount, productId);
        LoggerUtils.info(logger_key, "updateProductDiscountById,inDiscount:{},imDiscount:{},productId:{}", inDiscount, imDiscount, productId);
    }

    @Override
    public Map<String, Object> getProductDiscountByMap(Map<String, Object> productMap) {
        Long categoryType = productDiscountMapper.getCategoryType(Long.parseLong(productMap.get("categoryId").toString()));
        productMap.put("categoryType", categoryType);
        LoggerUtils.info(logger_key, "getProductDiscountByMap,productMap:{}", JsonTransformUtil.toJson(productMap));

        Map<String, Object> data = this.discount(productMap);
        LoggerUtils.info(logger_key, "getProductDiscountByMap,data:{},productMap:{}", JsonTransformUtil.toJson(data), JsonTransformUtil.toJson(productMap));
        return data;
    }

    @Override
    public Map<String, Object> getProductDiscountById(Long productId) {
        Map<String, Object> productMap = productDiscountMapper.getProduct(productId);
        LoggerUtils.info(logger_key, "getProductDiscountById,productId:{}", productId);

        Map<String, Object> data = this.discount(productMap);
        LoggerUtils.info(logger_key, "getProductDiscountById,data:{},productMap:{}", JsonTransformUtil.toJson(data), JsonTransformUtil.toJson(productMap));
        return data;
    }

    @Transactional
    @Override
    public void updateProductSeasonAndDiscountById(Long productId, String seasonCode) {
        productDiscountMapper.updateProductSeasonCodeById(productId, seasonCode);
        this.updateProductDiscountById(productId);
        LoggerUtils.info(logger_key, "updateProductSeasonAndDiscountById,productId:{},seasonCode:{}", productId, seasonCode);
    }

    @Transactional
    @Override
    public void updateProductPriceAndDiscountById(Long productId, BigDecimal retailPrice) {
        productDiscountMapper.updateProductPriceById(productId, retailPrice);
        this.updateProductDiscountById(productId);
        LoggerUtils.info(logger_key, "updateProductPriceAndDiscountById,productId:{},retailPrice:{}", productId, retailPrice);
    }

    private Map<String, Object> discount(Map<String, Object> productMap) {
        Map<String, Object> data = new HashMap<>();

        // boutique
        ProductDiscount boutiqueDiscount = this.getDiscount(productMap, boutiqueType);
        boutiqueDiscount = this.getDiscount(boutiqueDiscount);
        data.put("inDiscount", boutiqueDiscount);

        // im
        ProductDiscount imDiscount = this.getDiscount(productMap, imType);
        imDiscount = this.getAlgorithmDiscount(boutiqueDiscount.getDiscount(), imDiscount);
        if (StringUtils.isBlank(imDiscount.getDiscountLevel())) {
            imDiscount = this.getDiscount(imDiscount);
        }

        data.put("imDiscount", imDiscount);
        data.put("inDiscount", boutiqueDiscount);
        return data;
    }

    private ProductDiscount getDiscount(Map<String, Object> productMap, Long priceType) {
        ProductDiscount productDiscount = new ProductDiscount();
        productDiscount.setVendorId(Long.parseLong(productMap.get("vendorId").toString()));
        productDiscount.setCategoryId(Long.parseLong(productMap.get("categoryId").toString()));
        productDiscount.setBrandId(Long.parseLong(productMap.get("brandId").toString()));
        productDiscount.setSeasonCode(productMap.get("seasonCode").toString());
        productDiscount.setGroupId(productMap.get("groupId") == null ? null : Long.parseLong(productMap.get("groupId").toString()));
        productDiscount.setCategoryType(Long.parseLong(productMap.get("categoryType").toString()));
        productDiscount.setPriceType(priceType);
        productDiscount.setProductId(productMap.get("productId") == null ? null : Long.parseLong(productMap.get("productId").toString()));
        return productDiscount;
    }

    private ProductDiscount getAlgorithmDiscount(int boutiqueDiscount, ProductDiscount productDiscount) {
        Long imPriceAlgorithmId = productDiscountMapper.getImPriceAlgorithm(productDiscount.getSeasonCode(), productDiscount.getCategoryType(),
                productDiscount.getVendorId());

        if (imPriceAlgorithmId == null) {
            return productDiscount;
        }

        Integer imDiscountOff;
        Map<Long, List<ImPriceDiscountMapping>> mapBrandMapping = null;
        Map<Long, Map<Integer, Integer>> brandDiscountMapping = null;
        if (productDiscount.getProductId() != null) {
            Long burstingCount = productDiscountMapper.getBurstingByProductIdCount(productDiscount.getProductId());
            if (burstingCount != null && burstingCount.intValue() > 0) {
                //爆款
                mapBrandMapping = iPriceRuleService.getHotImBrandRuleMapping();
                brandDiscountMapping = iPriceRuleService.convertDiscountMapping(mapBrandMapping);
            }
        }

        if (mapBrandMapping == null || brandDiscountMapping == null) {
            mapBrandMapping = iPriceRuleService.getImBrandRuleMapping(imPriceAlgorithmId);
            brandDiscountMapping = iPriceRuleService.convertDiscountMapping(mapBrandMapping);
        }

        imDiscountOff = iPriceRuleService.getImDiscount(productDiscount.getBrandId(), (long) boutiqueDiscount, brandDiscountMapping);
        if (imDiscountOff == null) {
            imDiscountOff = productDiscountMapper.getImDefaultDiscount();
        }
        productDiscount.setDiscountLevel("getAlgorithmDiscount");
        productDiscount.setDiscount(imDiscountOff.intValue());
        return productDiscount;
    }

    private ProductDiscount getDiscount(ProductDiscount productDiscount) {
        Long priceChangeRuleId = productDiscountMapper.getPriceChangeRule(productDiscount.getSeasonCode(), productDiscount.getCategoryType(),
                productDiscount.getPriceType(), productDiscount.getVendorId());
        productDiscount.setPriceChangeRuleId(priceChangeRuleId);

        if (this.getProductDiscount(productDiscount)) {
            return productDiscount;
        }

        if (this.getProductGroupDiscount(productDiscount)) {
            return productDiscount;
        }

        if (this.getThreeCategoryDiscount(productDiscount)) {
            return productDiscount;
        }

        if (this.getSecondCategoryDiscount(productDiscount)) {
            return productDiscount;
        }

        if (this.getDefaultSecondCategoryDiscount(productDiscount)) {
            return productDiscount;
        }

        if (productDiscount.getPriceType().intValue() == imType.intValue()) {
            productDiscount.setDiscount(productDiscountMapper.getImDefaultDiscount());
            productDiscount.setDiscountLevel("getImDefaultDiscount");
            return productDiscount;
        }

        if (productDiscount.getPriceType().intValue() == boutiqueType.intValue()) {
            productDiscount.setDiscount(productDiscountMapper.getBoutiqueDefaultDiscount());
            productDiscount.setDiscountLevel("getBoutiqueDefaultDiscount");
            return productDiscount;
        }
        return null;
    }

    private boolean getDefaultSecondCategoryDiscount(ProductDiscount productDiscount) {
        Integer discount = productDiscountMapper.getSecondCategoryDiscount(productDiscount.getPriceChangeRuleId(), 0L, productDiscount.getCategoryId());
        if (discount != null) {
            productDiscount.setDiscount(discount);
            productDiscount.setDiscountLevel("getSecondCategoryDiscount");
            return true;
        }
        return false;
    }

    private boolean getSecondCategoryDiscount(ProductDiscount productDiscount) {
        Integer discount = productDiscountMapper.getSecondCategoryDiscount(productDiscount.getPriceChangeRuleId(), productDiscount.getBrandId(),
                productDiscount.getCategoryId());
        if (discount != null) {
            productDiscount.setDiscount(discount);
            productDiscount.setDiscountLevel("getSecondCategoryDiscount");
            return true;
        }
        return false;
    }

    private boolean getThreeCategoryDiscount(ProductDiscount productDiscount) {
        Integer discount = productDiscountMapper.getThreeCategoryDiscount(productDiscount.getPriceChangeRuleId(), productDiscount.getBrandId(),
                productDiscount.getCategoryId());
        if (discount != null) {
            productDiscount.setDiscount(discount);
            productDiscount.setDiscountLevel("getThreeCategoryDiscount");
            return true;
        }
        return false;
    }

    private boolean getProductGroupDiscount(ProductDiscount productDiscount) {
        if (productDiscount.getGroupId() != null) {
            Integer discount = productDiscountMapper.getProductGroupDiscount(productDiscount.getPriceChangeRuleId(), productDiscount.getGroupId());

            if (discount != null) {
                productDiscount.setDiscount(discount);
                productDiscount.setDiscountLevel("getProductGroupDiscount");
                return true;
            }
        }
        return false;
    }

    private boolean getProductDiscount(ProductDiscount productDiscount) {
        if (productDiscount.getProductId() != null) {
            Integer discount = productDiscountMapper.getProductDiscount(productDiscount.getPriceChangeRuleId(), productDiscount.getProductId());

            if (discount != null) {
                productDiscount.setDiscount(discount);
                productDiscount.setDiscountLevel("getProductDiscount");
                return true;
            }
        }
        return false;
    }
}
